package com.example.electricbicycle.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.electricbicycle.po.User;
import com.example.electricbicycle.service.UserService;
import com.example.electricbicycle.service.UserServiceImpl;


@WebServlet("/AddUserServlet")
public class AddUserServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.getRequestDispatcher("/admin/adduser.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置请求编码
        request.setCharacterEncoding("UTF-8");

        // 获取参数
        String username = request.getParameter("name");
        String password = request.getParameter("password");
        String role = request.getParameter("role");

        // 参数验证
        if (username.isEmpty() || password.isEmpty()) {
            request.setAttribute("errorMsg", "用户名和密码不能为空");
            request.getRequestDispatcher("/admin/adduser.jsp").forward(request, response);
            return;
        }

        // 创建用户对象（密码固定为123456）
        User newUser = new User();
        newUser.setName(username);
        newUser.setPassword("123456"); // 初始密码固定
        newUser.setRole(Integer.parseInt(role));

        // 添加用户
        boolean success = userService.addUser(newUser);

        if (success) {
            request.setAttribute("successMsg", "用户添加成功");
            response.sendRedirect(request.getContextPath() + "/UserListServlet");
        } else {
            request.setAttribute("errorMsg", "用户名已存在或数据库错误");
            request.getRequestDispatcher("/admin/adduser.jsp").forward(request, response);
        }
    }
}
